<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="兑换码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入唯一兑换码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用状态" prop="isUsed">
        <el-select v-model="queryParams.isUsed" placeholder="请选择使用状态" clearable>
          <el-option value="0" label="未使用"/>
          <el-option value="1" label="已使用"/>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="过期时间" prop="expireTime">-->
<!--        <el-date-picker clearable-->
<!--                        v-model="queryParams.expireTime"-->
<!--                        type="date"-->
<!--                        value-format="yyyy-MM-dd"-->
<!--                        placeholder="请选择过期时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['reward:code:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['reward:code:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['reward:code:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['reward:code:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="codeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="订单号" align="center" prop="orderId"/>
      <el-table-column label="唯一兑换码" align="center" prop="code"/>
      <el-table-column label="使用状态" align="center" prop="isUsed">
        <template slot-scope="scope">
          <span>{{ scope.row.isUsed == 1 ? '已使用' : '未使用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['reward:code:edit']">修改</el-button>-->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['reward:code:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-EditPen" @click="CheckCode(scope.row)" v-if="Checkopen">核验</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品兑换码对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单号"/>
        </el-form-item>
        <el-form-item label="唯一兑换码" prop="code">
          <el-input v-model="form.code" placeholder="请输入唯一兑换码"/>
        </el-form-item>
        <el-form-item label="使用状态" prop="isUsed">
          <el-select v-model="form.isUsed" placeholder="请选择使用状态">
            <el-option value="0" label="未使用"/>
            <el-option value="1" label="已使用"/>
          </el-select>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker clearable
                          v-model="form.expireTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择过期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCode, getCode, delCode, addCode, updateCode, checkCodeDie} from "@/api/reward/code";
import {getInfo} from "@/api/login";
// import { getInfo } from "@/api/system/user";
export default {
  name: "Code",
  data() {
    return {
      Checkopen:false,
      // 用户角色ID
      userRoleId: null,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      codeList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        code: null,
        isUsed: null,
        expireTime: null
      },
      form: {},
      rules: {
        orderId: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "唯一兑换码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.fetchUserRoleId(); // 获取用户信息
  },
  methods: {
    fetchUserRoleId() {
      // 调用后端接口获取用户信息
      getInfo().then(response => {
        if (response.roles[0]=='admin'){
          this.Checkopen=true;
        }
      });
    },
    CheckCode(row) {
      const { id, isUsed } = row;

      // 判断是否已使用
      if (isUsed === 1) {
        this.$modal.msgWarning("该兑换码已过期/已兑换，无法进行核验");
        return;
      }

      // 确认是否执行核验操作
      this.$modal.confirm('是否确认核验兑换码编号为"' + id + '"的数据项？').then(() => {
        console.log(row);
        // 调用 checkCodeDie API
        return checkCodeDie(row);
      }).then(response => {
        // 提示成功信息
        this.$modal.msgSuccess("核验成功");
        // 刷新列表数据
        this.getList();
      }).catch(() => {
        // 捕获取消或错误情况
        this.$modal.msgError("核验失败");
      });
    },
    getList() {
      this.loading = true;
      listCode(this.queryParams).then(response => {
        // console.log(response);
        this.codeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        orderId: null,
        code: null,
        isUsed: null,
        expireTime: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品兑换码";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCode(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品兑换码";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCode(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCode(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品兑换码编号为"' + ids + '"的数据项？').then(function() {
        return delCode(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('reward/code/export', {
        ...this.queryParams
      }, `code_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
